﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SDT.Lib.Common;
using System.Linq.Dynamic;
using SDT.Lib.Helpers;
using SDT.Model;
using SDT.Admin.ViewModels;
using SDT.Lib.Paging;
using SDT.Admin.Properties;
using System.IO;
namespace SDT.Admin.Controllers
{
	[RoleHelper(Roles = RoleSystem.Dictionary)]
    public class CompanyController : Controller
    {
        /// <summary>
        /// Created by Vietlv
        /// Created date 06/07/2011
        /// Description: Manage Company - Class Company controler;
        /// </summary>

        SDTDataContext eDataContext = new SDTDataContext();

        #region GET: /Company/Index
        public ActionResult Index(int? page)
        {
            try
            {
					if (!page.HasValue) page = 1;
                    string order = UserState.getUserStateFromRequest("category.order", "order", "id").ToString();
                    string orderDir = UserState.getUserStateFromRequest("category.orderDir", "orderDir", "desc").ToString();
					int currentPub = Convert.ToInt32(UserState.getUserStateFromRequest("Comment.ActivityYN", "ActivityYN", 0));
					string keyword = UserState.getUserStateFromRequest("Company.Keyword", "Keyword", "").ToString();
					int pageSize = int.Parse(UserState.getUserStateFromRequest("Company.pageSize", "PageSize", 20).ToString());
					var ActivityYNList = Utils.StringToDictionary(Settings.Default.CommentPubYN.ToString(), ",");

					var companies = eDataContext.Companies
					   .Where(cm => currentPub > 0 ? cm.ActiveYN == (currentPub == 1 ? true : false) : true)
					   .Where(p => (string.IsNullOrEmpty(keyword) ? true :
									(p.Name.ToString().ToLower().Contains(keyword.ToLower().Trim())
									))).OrderBy(string.Format("{0} {1}", order, orderDir)).ToPagedList(page.Value - 1, pageSize);
                    var city = eDataContext.Cities.ToList();
                    ViewData["orderDir"] = orderDir;
                    ViewData["order"] = order;

                    return View(new CompanyIndexViewModel
                    {
						Companies = companies,
                        Cities = city,
						ListActivityYN = ActivityYNList,
						Keyword = keyword,
						CurrentActivityYN = currentPub
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Company/Details/5

        public ActionResult Details(int id)
        {
            var company = eDataContext.Companies.Where(c => c.ID == id).SingleOrDefault();
            var listCity = eDataContext.Cities.ToList();
            var listCompanyType = (from n in eDataContext.CompanyTypeMaps
                                  .Where(n => n.CompanyID == id)
                                  select n.CompanyType).ToList();
            var imgRootUrl = Settings.Default.SiteRootUrl + Settings.Default.CompanyImageRreviewUrlPrefix;  
            return View(new CompanyIndexViewModel
            {
                Company = company,
                Cities = listCity,
                CompanyTypes = listCompanyType,
                ImageRootUrl = imgRootUrl
            });
        }
        #endregion

        #region GET: /Company/Create
        public ActionResult Create()
        {
            List<SelectListItem> listC = eDataContext.Cities
                                                    .Select(c => new SelectListItem()
                                                    {
                                                        Value = c.ID.ToString(),
                                                        Text = c.Name
                                                    }).ToList();
            var listCompanyType = eDataContext.CompanyTypes.ToList();
            return View(new CompanyIndexViewModel { 
                ListCity = listC,
                CompanyTypes = listCompanyType
            });
        }
        #endregion

        #region POST: /Company/Create
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(CompanyIndexViewModel c)
        {
            try
            {
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                // TODO: Add insert logic here
                UpdateModel(c);
                var pid = Request["CityID"] != "" ? Utils.ParseInt(Request["CityID"]) : 0;
                if (pid > 0) c.Company.CityID = pid;
                c.Company.AddBy = UserManager.GetUserId();
                c.Company.AddDate = DateTime.Now;

                eDataContext.Companies.InsertOnSubmit(c.Company);
                eDataContext.SubmitChanges();
                // Insert CompanyTypeMap
                var listCompanyType = eDataContext.CompanyTypes.ToList();
                foreach (var item in listCompanyType)
                {
                    var isSelected = Request["CompanyType." + item.ID] != null && Request["CompanyType." + item.ID].ToString().Equals("false") == false ? true : false;
                    if (isSelected == true)
                    {
                        var companyTypeMap = new CompanyTypeMap();
                        companyTypeMap.CompanyID = c.Company.ID;
                        companyTypeMap.CompanyTypeID = item.ID;
                        eDataContext.CompanyTypeMaps.InsertOnSubmit(companyTypeMap);
                        eDataContext.SubmitChanges();
                    }
                }
                // Upload file image
                HttpPostedFileBase fileName = Request.Files["CompanyFile"];
                if (fileName != null && fileName.ContentLength > 0)
                {
                    c.Company.ImagePath = Path.GetFileName(fileName.FileName);
                    Uploads.UploadFile(fileName, string.Format("{0}\\{1}", Settings.Default.SiteRootPath, Settings.Default.CompanyRootPath), "" + c.Company.ID);
                }
                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();

                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Company/Edit/5
        public ActionResult Edit(int id)
        {
            List<SelectListItem> listC = eDataContext.Cities
                                                    .Select(c => new SelectListItem()
                                                    {
                                                        Value = c.ID.ToString(),
                                                        Text = c.Name
                                                    }).ToList();
            List<SelectListItem> listD = eDataContext.Districts
                                                    .Where(d => d.CityID == id)
                                                    .Select(d => new SelectListItem()
                                                    {
                                                        Value = d.ID.ToString(),
                                                        Text = d.Name
                                                    }).ToList();
            var company = eDataContext.Companies.Where(c => c.ID == id).SingleOrDefault();
            var listCompanyTypes = eDataContext.CompanyTypes.ToList();
            var listCompanyTypeMap = eDataContext.CompanyTypeMaps.Where(e => e.CompanyID == id).ToList();
            return View(new CompanyEditViewModel
            {
               ListCity = listC,
               ListDistrict = listD,
                Company = company,
                CompanyTypes = listCompanyTypes,
                CompanyTypeMaps = listCompanyTypeMap,
                ImageRootUrl = Settings.Default.SiteRootUrl+ Settings.Default.CompanyImageRreviewUrlPrefix
            });
        }
        #endregion
       
        #region POST: /Company/Edit/5
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, CompanyEditViewModel c)
        {
            try
            {
                // TODO: Add update logic here
                if (eDataContext.Connection.State == System.Data.ConnectionState.Closed) eDataContext.Connection.Open();
                eDataContext.Transaction = eDataContext.Connection.BeginTransaction();
                c.Company = eDataContext.Companies.Where(e => e.ID == id).SingleOrDefault();
                
                var pid = Request["CityID"] != "" ? Utils.ParseInt(Request["CityID"]) : 0;
                if (pid > 0) {c.Company.CityID = pid;}
                UpdateModel(c);
                c.Company.ModifyBy = UserManager.GetUserId();
                c.Company.ModifyDate = DateTime.Now;
                eDataContext.SubmitChanges();
                
                // Test logo different null;
                HttpPostedFileBase fileName = Request.Files["CompanyFile"];
                if (fileName != null && fileName.ContentLength > 0)
                { 
                    // Delete olde logo;
                    if (!string.IsNullOrEmpty(c.Company.ImagePath) && System.IO.File.Exists(string.Format("{0}{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.CompanyImageRreviewUrlPrefix, "" + c.Company.ID + "_" + c.Company.ImagePath)))
                        Uploads.DeleteFile(string.Format("{0}\\{1}\\{2}", Settings.Default.SiteRootPath, Settings.Default.CompanyImageRreviewUrlPrefix, "" + c.Company.ID + "_" + c.Company.ImagePath));

                    //DO upload new image
                    c.Company.ImagePath = Path.GetFileName(fileName.FileName);
                    Uploads.UploadFile(fileName, string.Format("{0}{1}", Settings.Default.SiteRootPath, Settings.Default.CompanyRootPath), "" + c.Company.ID);
                }
                // Update CompanyTypeMap
                var list = eDataContext.CompanyTypeMaps.Where(e => e.CompanyID == id).ToList();
                eDataContext.CompanyTypeMaps.DeleteAllOnSubmit(list);
                foreach (var item in eDataContext.CompanyTypes)
                {
                    var isSelected = Request["CompanyType." + item.ID] != null && (Request["CompanyType." + item.ID]).ToString().Equals("false") == false ? true : false;
                    if (isSelected == true)
                    {
                        var companyTypeMap = new CompanyTypeMap();
                        companyTypeMap.CompanyID = c.Company.ID;
                        companyTypeMap.CompanyTypeID = item.ID;
                        eDataContext.CompanyTypeMaps.InsertOnSubmit(companyTypeMap);
                        eDataContext.SubmitChanges();
                    }
                }
                eDataContext.SubmitChanges();
                eDataContext.Transaction.Commit();
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                eDataContext.Transaction.Rollback();
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region GET: /Company/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                    var item = eDataContext.Companies.Single(e => e.ID == id);
                    return View(item);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion

        #region POST: /Company/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                    var item = eDataContext.Companies.Single(e => e.ID == id);
                    if (item != null)
                    {
                        var listCompanyArtMap = eDataContext.ArticleCompanyMaps.Where(e => e.CompanyID == id).ToList();
                        eDataContext.ArticleCompanyMaps.DeleteAllOnSubmit(listCompanyArtMap);

                        var listCompanyVideoMap = eDataContext.VideoCompanyMaps.Where(e => e.CompanyID == id).ToList();
                        eDataContext.VideoCompanyMaps.DeleteAllOnSubmit(listCompanyVideoMap);

                        var listCompanyTypeMap = eDataContext.CompanyTypeMaps.Where(e => e.CompanyID == id).ToList();
                        eDataContext.CompanyTypeMaps.DeleteAllOnSubmit(listCompanyTypeMap);
                        eDataContext.Companies.DeleteOnSubmit(item);
                        eDataContext.SubmitChanges();
                    }
                    return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        #endregion
    }
}
